import {
  _decorator,
  Component,
  Node,
  Collider2D,
  Contact2DType,
  IPhysics2DContact,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("BaseRoles")
export class BaseRoles extends Component {
  @property
  speed: number = 100;

  @property
  hp: number = 1;

  @property
  animHit: string = "";

  @property
  animDown: string = "";

  protected collider: Collider2D = null;
  protected haveDead: boolean = false;

  start() {
    // 注册碰撞体的回调函数
    this.collider = this.getComponent(Collider2D);
    if (this.collider) {
      this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  update(deltaTime: number) {
    if (this.hp > 0) {
      this.updateMovement(deltaTime);
    }
    this.checkBoundary();
  }

  protected updateMovement(deltaTime: number) {
    // 子类重写此方法实现具体的移动逻辑
  }

  protected checkBoundary() {
    // 超出屏幕范围销毁
    if (this.node.position.y < -580) {
      this.node.destroy();
    }
  }

  protected onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    // 子类重写此方法实现具体的碰撞逻辑
  }

  protected onDestroy(): void {
    // 取消注册碰撞回调
    if (this.collider) {
      this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
  }

  protected dead() {
    if (this.haveDead) return;

    if (this.collider) {
      this.collider.enabled = false;
    }

    this.scheduleOnce(function () {
      this.node.destroy();
    }, 1);

    this.haveDead = true;
  }

  killNow() {
    if (this.hp <= 0) return;
    this.hp = 0;
    this.dead();
  }
}
